package net.sunofbeach.blog.services.impl;

import lombok.extern.slf4j.Slf4j;
import net.sunofbeach.blog.dao.NavigationDao;
import net.sunofbeach.blog.pojo.Navigation;
import net.sunofbeach.blog.pojo.PageList;
import net.sunofbeach.blog.pojo.SobUser;
import net.sunofbeach.blog.response.ResponseResult;
import net.sunofbeach.blog.services.INavigationService;
import net.sunofbeach.blog.services.IUserService;
import net.sunofbeach.blog.utils.Constants;
import net.sunofbeach.blog.utils.IdWorker;
import net.sunofbeach.blog.utils.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class NavigationServiceImpl extends BaseService implements INavigationService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private NavigationDao navigationDao;


    @Override
    public ResponseResult postNavigation(Navigation navigation) {
        //检查用户，获取到用户对象
        SobUser sobUser = userService.checkSobUser();
        //未登录
        if (sobUser == null) {
            return ResponseResult.ACCOUNT_NOT_LOGIN();
        }
        //检查数据
        //title,分类ID，内容，类型，摘要，标签
        String name = navigation.getName();

        if (TextUtils.isEmpty(name)) {

            return ResponseResult.FAILED("导航标题不可以为空");
        }

        String description = navigation.getDescription();

        if (TextUtils.isEmpty(description)) {

            return ResponseResult.FAILED("导航描述不可以为空");
        }

        String cover = navigation.getCover();
        if (TextUtils.isEmpty(cover)) {
            return ResponseResult.FAILED("导航封面不可以为空");
        }

        String url = navigation.getUrl();
        if (TextUtils.isEmpty(url)) {
            return ResponseResult.FAILED("导航跳转链接不可以为空");
        }

        String navigationId = navigation.getId();

        if (TextUtils.isEmpty(navigationId)) {
            //新内容，数据库里没有
            //补充数据，ID，创建时间，用户ID，更新时间
            navigation.setId(idWorker.nextId() + "");
            navigation.setCreateTime(new Date());

        }

        String state = navigation.getState();
        if (TextUtils.isEmpty(state)) {
            navigation.setState("1");
        }

        navigationDao.save(navigation);
        return ResponseResult.SUCCESS("导航添加成功").setData(navigation);
    }

    @Override
    public ResponseResult listNavigations(int page, int size, String keyword, String categoryId, String state) {
        //处理一下size和page
        page = checkPage(page);
        size = checkSize(size);

        //创建分页和排序条件
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, size, sort);


        Page<Navigation> all = navigationDao.findAll(new Specification<Navigation>() {
            @Override
            public Predicate toPredicate(Root<Navigation> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {

                List<Predicate> predicates = new ArrayList<>();

                //判断是否有传参数
                if (!TextUtils.isEmpty(state)) {
                    Predicate statePre = cb.equal(root.get("state").as(String.class), state);
                    predicates.add(statePre);
                }
                if (!TextUtils.isEmpty(categoryId)) {
                    Predicate categoryPre = cb.equal(root.get("categoryId").as(String.class), categoryId);
                    predicates.add(categoryPre);
                }
                if (!TextUtils.isEmpty(keyword)) {
                    Predicate titlePre = cb.like(root.get("name").as(String.class), "%" + keyword + "%");
                    predicates.add(titlePre);
                }
                Predicate[] preArray = new Predicate[predicates.size()];
                predicates.toArray(preArray);
                return cb.and(preArray);
            }
        }, pageable);

        //处理查询条件
        PageList<Navigation> result = new PageList<>();
        //解析page
        result.parsePage(all);

        //返回结果
        return ResponseResult.SUCCESS("获取列表成功").setData(result);

    }

    @Override
    public ResponseResult getNavigationById(String navigationId) {

        //查询出文章
        Navigation navigation = navigationDao.findOneById(navigationId);
        if (navigation == null) {
            return ResponseResult.FAILED("导航不存在");
        }
        //返回结果
        return ResponseResult.SUCCESS("获取导航成功.").setData(navigation);
    }

    @Override
    public ResponseResult getNavigationByState(String State) {
        //查询出文章
        Navigation navigation = navigationDao.findOneByState(State);
        if (navigation == null) {
            return ResponseResult.FAILED("导航不存在");
        }
        //返回结果
        return ResponseResult.SUCCESS("获取导航成功.").setData(navigation);
    }

    @Override
    public ResponseResult updateNavigation(String navigationId, Navigation navigation) {
        //先找出来
        Navigation navigationFromDb = navigationDao.findOneById(navigationId);
        if (navigationFromDb == null) {
            return ResponseResult.FAILED("导航不存在");
        }
        //内容修改
        String name = navigation.getName();
        if (!TextUtils.isEmpty(name)) {
            navigationFromDb.setName(name);
        }

        //内容修改
        String description = navigation.getDescription();
        if (!TextUtils.isEmpty(description)) {
            navigationFromDb.setDescription(description);
        }


        String cover = navigation.getCover();
        if (!TextUtils.isEmpty(cover)) {
            navigationFromDb.setCover(cover);
        }

        String categoryId = navigation.getCategoryId();
        if (!TextUtils.isEmpty(categoryId)) {
            navigationFromDb.setCategoryId(categoryId);
        }
        String url = navigation.getUrl();
        if (!TextUtils.isEmpty(url)) {
            navigationFromDb.setUrl(url);
        }

        String state = navigation.getState();
        if (!TextUtils.isEmpty(state)) {
            navigationFromDb.setState(state);
        }

        navigationFromDb.setUpdateTime(new Date());

        navigationDao.save(navigationFromDb);
        //返回结果
        return ResponseResult.SUCCESS("导航更新成功");


    }

    @Override
    public ResponseResult deleteNavigationById(String navigationId) {
        int result = navigationDao.deleteAllById(navigationId);
        if (result > 0) {
            return ResponseResult.SUCCESS("导航删除成功");
        }
        return ResponseResult.FAILED("导航不存在");
    }

    @Override
    public ResponseResult topNavigation(String navigationId) {
        //必须是已经发布的，才可以指定
        Navigation navigation = navigationDao.findOneById(navigationId);
        if (navigation == null) {
            return ResponseResult.FAILED("导航不存在");
        }
        String state = navigation.getState();

        if (Constants.Navigation.STATE_PUBLISH.equals(state)) {
            //置顶值是3，注意一下
            navigation.setState(Constants.Navigation.STATE_TOP);
            navigationDao.save(navigation);
            return ResponseResult.SUCCESS("导航置顶成功");
        }
        if (Constants.Navigation.STATE_TOP.equals(state)) {
            navigation.setState(Constants.Navigation.STATE_PUBLISH);
            navigationDao.save(navigation);
            return ResponseResult.SUCCESS("已取消置顶");
        }
        return ResponseResult.FAILED("不支持该操作");
    }

    @Override
    public ResponseResult getNavigationByIdForAdmin(String navigationId) {
        //查询出文章
        Navigation navigation = navigationDao.findOneById(navigationId);
        if (navigation == null) {
            return ResponseResult.FAILED("导航不存在");
        }

        //返回结果
        return ResponseResult.SUCCESS("获取导航成功.").setData(navigation);
    }

    @Override
    public ResponseResult listNavigationByCategoryId(int page, int size, String navigationCategoryId) {
        page = checkPage(page);
        size = checkSize(size);
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        Page<Navigation> all = navigationDao.findAll(new Specification<Navigation>() {
            @Override
            public Predicate toPredicate(Root<Navigation> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                Predicate categoryIdPre = cb.equal(root.get("categoryId").as(String.class), navigationCategoryId);
                Predicate statePublishPre = cb.equal(root.get("state").as(String.class), Constants.Navigation.STATE_PUBLISH);
                Predicate stateTopPre = cb.equal(root.get("state").as(String.class), Constants.Navigation.STATE_TOP);
                Predicate or = cb.or(statePublishPre, stateTopPre);
                return cb.and(or, categoryIdPre);
            }
        }, pageable);
        return ResponseResult.SUCCESS("获取导航列表成功").setData(all);
    }

    @Override
    public ResponseResult getNavigationCount() {
        return null;
    }
}
